﻿
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Gameplay.CharacterFramework
{ 
    public class WeaponManager:MonoBehaviour
    {
        [SerializeField]private List<GameObject> _weaponObjs;
        [SerializeField] private Transform _rightWeaponSlot;
        [SerializeField] private Transform _leftWeaponSlot;
        public Transform RightWeaponSlot => _rightWeaponSlot;
        public Transform LeftWeaponSlot => _leftWeaponSlot; 

        [HideInInspector]
        public Weapon CurrentWeapon;
        private Dictionary<int,Weapon> _weaponList=new Dictionary<int,Weapon>();

        private Role _owner;

        private void Awake()
        {
            _owner = GetComponent<Role>();
        }
        private void Start()
        {
            InitWeaponSystem();
            SelectWeapon(10006);
        }

        private void InitWeaponSystem()
        {
            foreach (var weaponObj in _weaponObjs)
            {
                GameObject obj=GameObject.Instantiate(weaponObj);
                
                EquipWeapon(obj);
                obj.SetActive(false);
            }
        }

        public void EquipWeapon(GameObject weaponPrefab) 
        {
            var weapon = weaponPrefab.GetComponent<Weapon>();
           
            if (weapon.Config.Type == WeaponType.Bow) 
            {
                weaponPrefab.transform.parent = _leftWeaponSlot;
            }
            else 
            {
                weaponPrefab.transform.parent = _rightWeaponSlot;
            }
            weaponPrefab.transform.localPosition = Vector3.zero;
            weaponPrefab.transform.localRotation = Quaternion.identity;
            weaponPrefab.transform.localScale = Vector3.one;
            weapon.Init(_owner,this);
            if (_weaponList.ContainsKey(weapon.Config.Id)) 
            {
                return;
            }
            _weaponList.Add(weapon.Config.Id, weapon);
        }

        public void SelectWeapon(int id) 
        {
            if (!_weaponList.ContainsKey(id))
            {
                Debug.LogWarning(id+"武器不存在");
                return;
            }
            
            if (CurrentWeapon != null)
            {
                CurrentWeapon.gameObject.SetActive(false);
            }
            CurrentWeapon = _weaponList[id];
            if (CurrentWeapon.Config.Controller!=null)
            {
                _owner.AnimationComponent.Anim.runtimeAnimatorController = CurrentWeapon.Config.Controller;
            }
            CurrentWeapon.gameObject.SetActive(true);
        }
    }
}
